package com.example.myproject.controller;

import com.example.myproject.model.ChatMessage;
import com.example.myproject.model.ChatMessageEntity;
import com.example.myproject.service.ChatService;
import com.example.myproject.security.JwtAuthenticationFilter;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.Instant;
import java.util.List;

@Controller
public class ChatController {

    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    @Autowired
    private ChatService chatService;

    @MessageMapping("/chat.join")
    public void joinChat(@Payload ChatMessage chatMessage,
                         SimpMessageHeaderAccessor headerAccessor) {
        JwtAuthenticationFilter.UserPrincipal principal = (JwtAuthenticationFilter.UserPrincipal) headerAccessor.getUser();
        if (principal == null) {
            System.err.println("Join chat failed: User not authenticated.");
            return;
        }
        chatMessage.setFrom(principal.getUsername());

        ChatMessage systemMessage = new ChatMessage();
        systemMessage.setType(ChatMessage.MessageType.SYSTEM);
        systemMessage.setContent(chatMessage.getFrom() + " 已加入聊天。");
        systemMessage.setTimestamp(Instant.now());
        systemMessage.setFrom("System");
        simpMessagingTemplate.convertAndSendToUser(principal.getUsername(), "/queue/messages", systemMessage);

        System.out.println("User " + chatMessage.getFrom() + " joined chat.");
    }

    @MessageMapping("/chat.private")
    public void sendPrivateMessage(@Payload ChatMessage chatMessage) {
        chatMessage.setType(ChatMessage.MessageType.CHAT);
        chatMessage.setTimestamp(Instant.now());

        // 保存消息，并判断接收方是否在线
        ChatMessageEntity savedMessageEntity = chatService.saveMessage(chatMessage);

        // 发送给接收方
        simpMessagingTemplate.convertAndSendToUser(
                chatMessage.getTo(), "/queue/messages", chatMessage);

        // 如果发送方和接收方不是同一个人，也给自己发送一份，确保状态正确显示（已读/未读）
        if (!chatMessage.getFrom().equals(chatMessage.getTo())) {
            ChatMessage messageForSender = new ChatMessage();
            messageForSender.setId(savedMessageEntity.getId()); // 传递ID以便前端更新
            messageForSender.setFrom(savedMessageEntity.getFromUser());
            messageForSender.setTo(savedMessageEntity.getToUser());
            messageForSender.setContent(savedMessageEntity.getContent());
            messageForSender.setType(ChatMessage.MessageType.valueOf(savedMessageEntity.getType().name()));
            messageForSender.setTimestamp(savedMessageEntity.getTimestamp());
            messageForSender.setReadStatus(savedMessageEntity.getReadStatus().name()); // 确保状态正确
            simpMessagingTemplate.convertAndSendToUser(chatMessage.getFrom(), "/queue/messages", messageForSender);
        }
    }

    @MessageMapping("/chat.read")
    public void markMessageAsRead(@Payload ChatMessage chatMessage) {
        // chatMessage: from (原始发送方), to (当前读取方)
        String originalSender = chatMessage.getFrom();
        String currentReader = chatMessage.getTo();

        // 标记消息为已读，并获取这些已读消息的DTO列表，以便通知原始发送方
        List<ChatMessage> updatedMessagesForSender = chatService.markMessagesAsReadAndRetrieveForSender(currentReader, originalSender);

        System.out.println("Marked messages from " + originalSender + " to " + currentReader + " as READ.");

        // 将这些已读消息推送给原始发送方，更新其UI上的消息状态
        for (ChatMessage msg : updatedMessagesForSender) {
            simpMessagingTemplate.convertAndSendToUser(originalSender, "/queue/messages", msg);
            System.out.println("Notifying " + originalSender + " about read message: " + msg.getContent() + " (status: " + msg.getReadStatus() + ")");
        }
    }

    @GetMapping("/api/chat/history/{user1}/{user2}")
    @ResponseBody
    public List<ChatMessage> getChatHistory(@PathVariable String user1, @PathVariable String user2) {
        return chatService.getConversationHistory(user1, user2);
    }
}